package ezonsport.android.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;

import ezonsport.android.core.stepSystem.StepData;
import ezonsport.android.data.DataHelper;
import ezonsport.android.data.OrmliteDataContext;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class FileManageService {

	private OrmliteDataContext ctx;

	public FileManageService(DataHelper dataHelper) {
		ctx = new OrmliteDataContext(dataHelper);
	}

	/**
	 * 创建运动数据文件(存放在应用程序文件目录下)
	 * 
	 * @param context
	 * @param fileName
	 * @param mode
	 */
	public void createSportDataFile(Context context, String fileName, int mode) {
		try {
			// 以mode模式打开文件输出流
			FileOutputStream fos = context.openFileOutput(fileName, mode);
			ObjectOutputStream out = new ObjectOutputStream(fos);

			// 创建对象
			Calendar calendar = Calendar.getInstance();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

			Random random = new Random();
			for (int i = 1; i < 10; i++) {
				calendar.set(2012, 6, i);// 添加数据：2012-7-1 —— 2012-7-9
				String dateString = dateFormat.format(calendar.getTime());
				StepData stepData = new StepData();
				stepData.setCollectTime(dateFormat.parse(dateString));
				stepData.setSteps(random.nextInt(4000));

				// 序列化对象
				out.writeObject(stepData);

			}
			StepData stepData = null;
			out.writeObject(stepData);// 用来标识文件结束
			out.close();
			Log.d("File", "write is success");

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 解析文件（从应用程序的数据文件夹里获取），并将数据存储到数据库中
	 * 
	 * @param context
	 * @param fileName
	 */
	public void storeFileToDB(Context context, String fileName) {
		try {
			String file = context.getFilesDir().toString() + "/" + fileName;
			// 打开文件输入流
			FileInputStream fis = context.openFileInput(fileName);
			ObjectInputStream in = new ObjectInputStream(fis);

			// 反序列化对象
			StepData stepData;
			while ((stepData = (StepData) in.readObject()) != null) {

				// 持久化对象
				ctx.add(stepData, StepData.class, long.class);

			}
			in.close();
			Log.d("File", "add is success");

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 在SD卡中创建数据文件
	 * 
	 * @param fileName
	 */
	public void createFileToSdcard(String fileName) {
		try {
			// 如果手机插入了SD卡，而且应用程序具有访问SD的权限
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				// 获取SD卡的目录
				File sdCardDir = Environment.getExternalStorageDirectory();
				File targetFile = new File(sdCardDir.getCanonicalPath() + "/"
						+ fileName);
				// 如果存在同名文件，先删除，再创建
				if (targetFile.exists()) {
					targetFile.delete();
					Log.d("File", "delete");
				}
				// 以追加模式打开文件输出流
				FileOutputStream fos = new FileOutputStream(targetFile, true);
				ObjectOutputStream out = new ObjectOutputStream(fos);

				// 创建对象
				Calendar calendar = Calendar.getInstance();
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

				Random random = new Random();
				for (int i = 1; i < 10; i++) {
					calendar.set(2012, 6, i);// 添加数据：2012-7-1 —— 2012-7-9
					String dateString = dateFormat.format(calendar.getTime());
					StepData stepData = new StepData();
					stepData.setCollectTime(dateFormat.parse(dateString));
					stepData.setSteps(random.nextInt(4000));

					// 序列化对象
					out.writeObject(stepData);

				}
				StepData stepData = null;
				out.writeObject(stepData);// 用来标识文件结束
				out.close();
				Log.d("File", "write is success");

			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	/**
	 * 解析SD卡中的文件，并将其内容存储到数据库中
	 * 
	 * @param fileName
	 */
	public void storeFileDataToDB(String fileName) {
		try {
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				// 获取SD卡的目录
				File sdCardDir = Environment.getExternalStorageDirectory();
				File targetFile = new File(sdCardDir.getCanonicalPath() + "/"
						+ fileName);
				// 如果SD卡中存在文件，则解析，否则存储失败
				if (targetFile.exists()) {
					//获取指定文件对应的输入流
					FileInputStream fis = new FileInputStream(targetFile);
					ObjectInputStream in = new ObjectInputStream(fis);

					// 反序列化对象
					StepData stepData;
					while ((stepData = (StepData) in.readObject()) != null) {

						// 持久化对象
						ctx.add(stepData, StepData.class, long.class);

					}
					in.close();
					Log.d("File", "add is success");

				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

}
